package com.csi.controller.user;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.csi.domain.Employee;
import com.csi.domain.User;
import com.csi.pojo.Result;
import com.csi.service.EmployeeService;
import com.csi.service.UserService;
import com.csi.service.impl.EmployeeServiceImpl;
import com.csi.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@WebServlet("/user/entryController")
public class EntryController extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置相应内容
        resp.setContentType("application/json;charset=utf-8");

        // 从请求体中获取JSON格式的数据
        BufferedReader reader = req.getReader();
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        JSONObject jsonObject = JSON.parseObject(sb.toString());

        PrintWriter out = resp.getWriter();

        Result result = new Result<>();

        Integer userId = null;
        List<Integer> roles = null;
        try {
            userId = jsonObject.getInteger("userId");
            JSONArray jsonArray = jsonObject.getJSONArray("roles");
            roles = jsonArray.toJavaList(Integer.class);
        } catch (NumberFormatException e) {
            result.setCode(400);
            result.setMsg("false");
            out.print(JSON.toJSONString(result));
            out.flush();
            out.close();
            return;
        }

        UserService userService = new UserServiceImpl();

        userService.entry(userId,roles);
        result.setCode(200);
        result.setMsg("success");

        out.print(JSON.toJSONString(result));
        out.flush();
        out.close();
    }


}
